<template>
    <section>
        <!--高级查询-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item>
                    <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" disabled @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="petOnsaleAuditLogs" :row-key="getRowKey" highlight-current-row v-loading="listLoading"
                  @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="petId" label="宠物ID">
            </el-table-column>
            <el-table-column prop="auditId" label="审核人员ID">
            </el-table-column>
            <el-table-column prop="auditTime" label="审核时间">
            </el-table-column>
            <el-table-column prop="state" label="状态">
                <template scope="scope">
                    <span v-if="scope.row.state==0" style="color: red">失败</span>
                    <span v-if="scope.row.state!=0" style="color: green">通过</span>
                </template>
            </el-table-column>
            <el-table-column prop="note" label="审核结果">
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                    <el-button size="small" disabled @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" disabled size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" disabled >批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                           :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑/新增界面-->
        <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" width="50%">
            <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
                <el-form-item label="宠物名称" prop="name">
                    <el-input v-model="saveForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="成本价">
                    <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="市场价">
                    <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="宠物图片">
                    <el-upload
                            class="upload-demo"
                            action="http://localhost:8080/fastDfs"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            list-type="picture">

                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <!--<view v-for="(item,index) in saveForm.resources" :key="index">111-->
                <!--</view>-->
                <!--<img :src="this.petOnsaleAuditLogUrl" style="width: 200px"></img>-->
                <el-form-item label="宠物类型">
                    <el-cascader v-model="saveForm.typeId"
                                 :options="petOnsaleAuditLogTrees"
                                 :props="{ checkStrictly: true,label:'name',value:'id' }"
                                 clearable></el-cascader>
                </el-form-item>
                <el-form-item label="所属店铺">
                    <el-select v-model="saveForm.shopId" clearable placeholder="请选择">
                        <el-option v-for="item in shops"
                                   :label="item.name"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="简介" prop="intro">
                    <!-- v-if="saveForm.petOnsaleAuditLogDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
                    <quill-editor v-model="saveForm.petOnsaleAuditLogDetail.intro" v-if="saveForm.petOnsaleAuditLogDetail" :options="quillOption">
                    </quill-editor>
                </el-form-item>
                <el-form-item label="领养须知" prop="orderNotice">
                    <quill-editor v-model="saveForm.petOnsaleAuditLogDetail.adoptNotice" v-if="saveForm.petOnsaleAuditLogDetail"
                                  :options="quillOption">
                    </quill-editor>
                </el-form-item>
                <!--<el-form-item label="宠物状态">
                    <el-radio-group v-model="saveForm.state">
                        <el-radio class="radio" :label="1">上架</el-radio>
                        <el-radio class="radio" :label="0">下架</el-radio>
                    </el-radio-group>
                </el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="saveFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    import util from '../../common/js/util'
    import {quillEditor} from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quillConfig from '../../common/js/quill-config';
    //import NProgress from 'nprogress'
    import {getPetOnsaleAuditLogListPage, removePetOnsaleAuditLog, batchRemovePetOnsaleAuditLog, editPetOnsaleAuditLog, addPetOnsaleAuditLog} from '../../api/api';

    export default {
        components: {
            quillEditor
        },
        data() {
            return {
                petOnsaleAuditLogs: [],
                totals: 0,//总数
                pageSize: 5,//每页数量
                currentPage: 1,//页数
                listLoading: false,//加载框
                title: '',//标题
                quillOption: quillConfig,//富文本
                //所属店铺
                shops: [],
                //宠物类型树
                petOnsaleAuditLogTrees: [],
                //petOnsaleAuditLogUrl:[],
                //宠物图片
                fileList: [],
                //高级查询参数
                keyword: '',
                // url: 'http://123.207.27.208',
                sels: [],//列表选中列

                saveFormVisible: false,//编辑/新增界面是否显示
                saveLoading: false,
                saveFormRules: {
                    name: [
                        {required: true, message: '请输入宠物名称', trigger: 'blur'}
                    ]
                },
                //编辑/新增界面数据
                saveForm: {
                    id: null,
                    name: '',
                    costprice: 0,
                    saleprice: 0,
                    typeId: null,
                    resources: '',
                    state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
                    shopId: null,
                    petOnsaleAuditLogDetail: {
                        intro: null,
                        adoptNotice: null
                    }
                },

            }
        },
        methods: {
            //高级查询
            keywordQuery() {
                this.currentPage = 1;
                this.getPetOnsaleAuditLogs()
            },
            //分页实现
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getPetOnsaleAuditLogs();
            },
            //获取部门列表
            getPetOnsaleAuditLogs() {
                let para = {
                    pageSize: this.pageSize,
                    currentPage: this.currentPage,
                    keyword: this.keyword
                };
                //开启加载框
                this.listLoading = true;
                //发送请求
                this.$http.post("/petOnsaleAuditLog", para).then(res => {
                    //给petOnsaleAuditLogs数组赋值
                    this.petOnsaleAuditLogs = res.data.data;
                    //给分页赋值
                    this.totals = res.data.totals;
                    //关闭加载框
                    this.listLoading = false;
                }).catch(res => {
                    this.$message.error("系统繁忙，正在骚扰程序猿")
                })

            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;//显示加载框
                    this.$http.delete("/petOnsaleAuditLog/" + row.id).then(res => {
                        this.listLoading = false;
                        if (res.data.success) {
                            this.$message.success("删除成功")
                            //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
                            var totalPage = Math.ceil(this.totals / this.pageSize); //总页数 = 最后一页
                            if ((this.totals - 1) % this.pageSize == 0 && this.currentPage == totalPage && this.currentPage != 1) {
                                this.currentPage = this.currentPage - 1;
                            }

                            this.getPetOnsaleAuditLogs();
                        } else {
                            this.$message.error("系统繁忙【500】")
                        }
                    }).catch(res => {
                        this.$message.error("系统繁忙【404.400】")
                    })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.title = "编辑";

                //弹出对话框
                this.saveFormVisible = true;

                //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝一份给{}
                this.saveForm = Object.assign({}, row);
                //处理fileList - 点击修改能够回显图片
                this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
                if(this.saveForm.resources){
                    // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
                    var arr = this.saveForm.resources.split(",");
                    for(var i = 0;i<arr.length;i++){
                        var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
                        this.fileList.push({"url":"http://123.207.27.208" + item});
                    }
                }
               // this.petOnsaleAuditLogUrl =  this.url +  this.saveForm.resources;
                // this.petOnsaleAuditLogUrl = JSON.parse(this.petOnsaleAuditLogUrl)
                //图片回显
                /*this.petOnsaleAuditLogUrl=[];
                this.petOnsaleAuditLogUrl =  this.saveForm.resources;
                this.petOnsaleAuditLogUrl = JSON.parse(this.petOnsaleAuditLogUrl);
                console.log(this.petOnsaleAuditLogUrl);
                var resourcesArr = this.petOnsaleAuditLogUrl.split(",");
                for(var i=0;i<resourcesArr.length;i++){
                    console.log("http://123.207.27.208"+resourcesArr[i])
                    this.fileList.push({url:"http://123.207.27.208"+resourcesArr[i]})
                }*/

            },
            //显示新增界面
            handleAdd: function () {
                this.title = "新增";
                //清除缓存
                this.fileList = [];
                this.saveFormVisible = true;
                this.saveForm = {
                    id: null,
                    name: '',
                    costprice: 0,
                    saleprice: 0,
                    typeId: null,
                    resources: '',
                    state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
                    shopId: null,
                    petOnsaleAuditLogDetail: {  //与后端实体类一致
                        intro: '',
                        adoptNotice: ''
                    }
                };
            },
            //编辑/新增
            saveSubmit: function () {
                this.$refs.saveForm.validate((valid) => {

                    /*this.saveForm.resources = JSON.stringify(this.saveForm.resources);*/

                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.saveLoading = true;
                            let para = Object.assign({}, this.saveForm);//数据赋值
                            //对上级部门的处理
                            var result = para.typeId;

                            //5种情况，不修改值为2，点击后不修改【2】，去掉上级部门【】，选择子部门【2,3,4】，直接清空null
                            if (Array.isArray(result)) {
                                if (result.length == null) {//空的
                                    para.typeId = null;
                                } else {//有数据就获取数据
                                    para.typeId = result[result.length - 1];
                                }
                            }
                            this.$http.put("/petOnsaleAuditLog", para).then(res => {
                                this.saveLoading = false;//关闭忙等框
                                this.saveFormVisible = false;//关闭会话框
                                if (res.data.success) {
                                    this.$message.success("保存成功");
                                    this.getPetOnsaleAuditLogs()
                                } else {
                                    this.$message.error("毁灭把，赶紧的【500】")
                                }
                            }).catch(rse => {
                                this.$message.error("啊哈哈哈哈，出错了【400.404】")
                            })
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认清除掉选中的人吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //ajax传递参数
                    this.$http.patch("/petOnsaleAuditLog", ids).then(res => {
                        this.listLoading = false;
                        if (res.data.success) {
                            this.$message.success("删除成功");
                            this.currentPage = 1;
                            this.getPetOnsaleAuditLogs()
                        } else {
                            this.$message.error("正在殴打程序员【500】")
                        }
                    }).catch(res => {
                        this.$message.error("正在毁灭地球【400.404】")
                    })
                }).catch(() => {

                });
            },
            getRowKey(row) {
                return row.id;
            },
            getShops() {
                this.$http.get("/shop").then(res => {
                    this.shops = res.data
                })
            },
            //上架
            onsale() {
                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if (!this.sels || this.sels.length < 1) {
                    this.$message({message: '你上架了一堆空气', type: 'error'});
                    return;
                }
                this.$confirm('确认上架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.post('/petOnsaleAuditLog/onsale', ids).then((res) => {
                        this.listLoading = false;
                        if (res.data.success) {
                            this.$message({
                                message: '上架成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
                        }
                        this.getPetOnsaleAuditLogs();
                    }).catch(res => {
                        this.$message({
                            message: "系统错误，请稍后重试!!!",
                            type: 'error'
                        });
                    })
                }).catch(() => {
                });
            },
            //下架
            offsale() {
                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if (!this.sels || this.sels.length < 1) {
                    this.$message({message: '你下架了一堆空气', type: 'error'});
                    return;
                }
                this.$confirm('确认下架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.post('/petOnsaleAuditLog/offsale', ids).then((res) => {
                        this.listLoading = false;

                        if (res.data.success) {
                            this.$message({
                                message: '下架成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
                        }
                        this.getPetOnsaleAuditLogs();
                    }).catch(res => {
                        this.$message({
                            message: "系统错误，请稍后重试!!!",
                            type: 'error'
                        });
                    })
                }).catch(() => {
                });
            },
            /*//图片上传
            handleSuccess(response, file, fileList) {
                console.log("===========")
                console.log(fileList);
                //resultObj 文件的服务器地址，放到数据库中
                //根据双向绑定 logo 就有值 1,2,3
                let resourcesTmp = '';
                if (fileList != null && fileList.length > 0) {
                    for (var i = 0; i < fileList.length; i++) {
                        if (i == 0) {
                            resourcesTmp = resourcesTmp + fileList[i].response.resultObj;
                        } else {
                            resourcesTmp = resourcesTmp + "," + fileList[i].response.resultObj;
                        }
                    }
                }
                this.saveForm.resources = resourcesTmp;
                console.log(this.saveForm.resources)
            },
            //图片删除
            handleRemove(file, fileList) {
                var filePath = file.response.resultObj;
                console.log(fileList)
                this.$http.delete("/common/fastDfs/?path=" + filePath)
                    .then(res => {
                        if (res.data.success) {
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    });

                //删除图片后移除data里面数据
                let resourcesTmp = '';
                if (fileList != null && fileList.length > 0) {
                    for (var i = 0; i < fileList.length; i++) {
                        if (i == 0) {
                            resourcesTmp = resourcesTmp + fileList[i].response.resultObj;
                        } else {
                            resourcesTmp = resourcesTmp + "," + fileList[i].response.resultObj;
                        }
                    }
                }
                this.saveForm.resources = resourcesTmp;
                console.log(this.saveForm.resources);
            }*/
            //图片上传成功之后的回调
            handleSuccess(response, file, fileList){
                //Object { success: true, msg: "操作成功", resultObj: "/group1/M00/00/E4/CgAIC2Lc91yAK-XNAAVL-CQTDAM697.jpg" }
                //1.对resources的处理 - 添加到数据库
                if(this.saveForm.resources){//有值返回true
                    this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
                }else{
                    this.saveForm.resources = response.resultObj;
                }

                //2.对fileList的处理 - 前端显示图片的
                this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
                if(this.saveForm.resources){
                    // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
                    var arr = this.saveForm.resources.split(",");
                    for(var i = 0;i<arr.length;i++){
                        var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
                        this.fileList.push({"url":"http://123.207.27.208" + item});
                    }
                }
            },
            handleRemove(file, fileList){
                //1.调用删除接口删除图片
                //Object { url:"http://123.207.27.208/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg"}
                //console.log(file);
                //http://localhost:8080/fastDfs?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
                var path = file.url.substring(file.url.indexOf("/group")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
                this.$http.delete("/fastDfs?path="+path).then(res=>{
                    if(res.data.success){
                        this.$message.success("删除成功")
                    }else{
                        this.$message.error("删除失败")
                    }
                })

                //2.对resource做处理
                // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg,/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
                if(this.saveForm.resources){
                    var arr = this.saveForm.resources.split(",");
                    for(var i = 0;i<arr.length;i++){
                        var item = arr[i];
                        if(path==item){//找到了删除的图片
                            arr.splice(i,1);//删除指定的图片
                        }
                    }
                    this.saveForm.resources = arr.join(",")
                }


                //3.对fileList的处理 - 前端显示图片的
                this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
                if(this.saveForm.resources){
                    // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
                    var arr = this.saveForm.resources.split(",");
                    for(var i = 0;i<arr.length;i++){
                        var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
                        this.fileList.push({"url":"http://123.207.27.208" + item});
                    }
                }
            }
        },
        mounted() {
            this.getPetOnsaleAuditLogs();
        }
    }

</script>

<style scoped>

</style>